package com.hyy.lotterysystem.service.Impl;

import com.hyy.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.hyy.lotterysystem.common.exception.ServiceException;
import com.hyy.lotterysystem.common.utils.CaptchaUtil;
import com.hyy.lotterysystem.common.utils.MailUtil;
import com.hyy.lotterysystem.common.utils.RedisUtil;
import com.hyy.lotterysystem.common.utils.RegexUtil;
import com.hyy.lotterysystem.dao.mapper.UserMapper;
import com.hyy.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    private static final Long VERIFICATION_CODE_TIMEOUT = 60*30L;

    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void sendVerificationCode(String email) {
        // 校验邮箱
        if (!RegexUtil.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //查询邮箱绑定人数
        int n=userMapper.countByMail(email);
        if(n==0){
            throw new ServiceException(ServiceErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST);
        }

        //生成唯一验证码
        String code = CaptchaUtil.getCaptcha(5);

        // 发送验证码
        String subject = "活动中心登录验证码";
        String content = "<div style=\"font-family:Arial,sans-serif;padding:20px;background:#f9f9f9;\">" +
                "<h2 style=\"color:#4CAF50;\">活动中心登录验证码</h2>" +
                "<p>您好，</p>" +
                "<p>您的登录验证码是：</p>" +
                "<div style=\"font-size:24px;font-weight:bold;color:#2196F3;margin:20px 0;\">" + code + "</div>" +
                "<p>请在30分钟内完成验证。</p>" +
                "<p style=\"color:#888;font-size:12px;\">如果不是您本人操作，请忽略此邮件。</p>" +
                "</div>";
        mailUtil.sendMailAndHtml(email,subject,content);

        //验证码存储到Redis中设置过期时间
        redisUtil.set(VERIFICATION_CODE_PREFIX + email, code, VERIFICATION_CODE_TIMEOUT);

    }

    @Override
    public String getVerificationCode(String email) {
        // 校验邮箱
        if (!RegexUtil.checkMail(email)) {
            throw new ServiceException(ServiceErrorCodeConstants.EMAIL_FORMAT_ERROR);
        }

        return redisUtil.get(VERIFICATION_CODE_PREFIX + email);
    }


}
